package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @PostMapping("/upload")
    public R uploadImg(MultipartFile file) throws IOException {
        //获取图片名称后缀
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        //生成图片名称
        String uuidName = UUID.randomUUID().toString();
        String imgName=uuidName+substring;
        file.transferTo(new File("d://myImg//"+imgName));

        return R.success(imgName);
    }

    //图片下载
    @GetMapping("/download")
    public void downLoadImg(String name, HttpServletResponse response) throws IOException {
        IOUtils.copy(new FileInputStream("d://myImg//"+name),response.getOutputStream());
    }
}
